import { isEmpty, merge, isFunction } from 'lodash-es'
import { getAndRemoveValue, isPromise } from '../utils'

/**
 * 配置表格操作栏
 */
export function configTableActionsColumn(
  tableConfig,
  createAndUpdateConfig,
  updateButton,
  deleteButton
) {
  const handle = getAndRemoveValue(tableConfig, 'handle')

  const btns = []
  // 添加编辑按钮
  if (updateButton) {
    btns.push(updateButton)
  }
  // 添加删除按钮
  if (deleteButton) {
    btns.push(deleteButton)
  }
  // 添加其他按钮
  const handleItems = handle && getAndRemoveValue(handle, 'items')
  if (handleItems) {
    btns.push(...handleItems)
  }

  // 设置按钮的尺寸，默认为mini
  const btnSize = handle && getAndRemoveValue(handle, 'btnSize')
  btns.forEach(btn => {
    (btn.options || (btn.options = {})).size = btnSize || 'mini'
  })

  if (!isEmpty(btns)) {
    const column = merge({
      label: '操作',
      options: { fixed: 'right', align: 'left', resizable: false }
    }, handle)
    btns.forEach(btn => {
      btn.options = Object.assign({ type: 'primary' }, btn.options)
    })
    configTableActionsColumnRender(
      column,
      btns,
      handle
    )
    tableConfig.columns.push(column)
  }
}

/**
 * 表格操作栏配置的render方法
 */
function configTableActionsColumnRender(
  column,
  btns,
  handle
) {
  // 关闭按钮loading的延迟时间
  const CLOSE_BTN_LOADING_DELAY = 500
  
  // 控制按钮loading属性
  const tableActionsColumnButtonLoadingArray = []
  const getRowItemLoading = function(vm, index) {
    if (!tableActionsColumnButtonLoadingArray[index]) {
      const obj = { ...btns.map(() => false ) }
      const observable = vm.$options._base.observable
      tableActionsColumnButtonLoadingArray[index] = observable(obj)
    }
    return tableActionsColumnButtonLoadingArray[index]
  }

  column.render = function(h, attrs) {
    const vm = attrs._self
    const rowItemLoading = getRowItemLoading(vm, attrs.$index)

    let content = btns.reduce((res, btn, index) => {
      if (!btn.show || btn.show(attrs.value)) {
        // 动态修改表格属性
        const opts = { name: btn.name, options: { ...btn.options }}
        if (btn.dynamicLoad) {
          btn.dynamicLoad.call(opts, attrs.value)
        }
        
        const onClick = () => {
          if (isFunction(btn.click)) {
            // 按钮点击事件是否返回Promise,是的话自动loading
            let isAsync
            const showLoading = () => (vm.$set(rowItemLoading, index, true))
            const cancelLoading = () => (vm.$set(rowItemLoading, index, false))
            const setData = (key, value) => {
              if (isAsync) {
                setTimeout(() => {
                  vm.$set(attrs.row, key, value)
                }, CLOSE_BTN_LOADING_DELAY)
              } else {
                vm.$set(attrs.row, key, value)
              }
            }
            const res = btn.click({ ...attrs.value }, { showLoading, cancelLoading, setData })
            if ((isAsync = isPromise(res))) {
              showLoading()
              res.finally(() => {
                setTimeout(cancelLoading, CLOSE_BTN_LOADING_DELAY)
              })
            }
          }
        }

        res.push(
          h('el-button', {
            props: Object.assign({ loading: rowItemLoading[index] }, opts.options),
            on: { click: onClick }
          }, [opts.name])
        )
      }
      return res
    }, [])

    if (handle && handle.transformVNodeContent) {
      content = handle.transformVNodeContent(content)
    }

    return h('div', {
      class: 'v-crud-table__actions'
    }, content)
  }
}
